﻿module Sustainalytics.EsgRatings.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class KeyESGIssuesController {

        private keyESGIssuesService: any;
        public selectedFile: any;
        public loading: boolean;
        public $scope: ng.IScope;
        public $rootScope: any;
        public uploadDetails: string;

        constructor(
            $scope: ng.IScope,
            $rootScope,
            $q: ng.IQService,
            $location: ng.ILocationService,
            $http: ng.IHttpService,
            KeyESGIssuesService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin) {

            $scope['keyESGIssues'] = this;

            this.$scope = $scope;
            this.$rootScope = $rootScope;
            this.keyESGIssuesService = KeyESGIssuesService;
        }

        public selectFile($files) {
            this.selectedFile = $files[0];

            if (!this.selectedFile) {
                this.uploadDetails = null;
            }
        }

        public uploadKeyESGIssuesFile() {
            this.uploadDetails = null;

            if (this.selectedFile) {
                if (this.selectedFile.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
                    this.selectedFile.type != "application/vnd.ms-excel") {
                    alert("File format not supported!");
                    this.selectedFile = null;
                }
                else {
                    this.$rootScope.loading = true;

                    var fileReader = new FileReader();
                    fileReader.onload = (rootScope => {
                        return e => this.keyESGIssuesService.uploadKeyESGIssuesFile(e.target.result, this.selectedFile.name, this.selectedFile.type)
                            .then(() => alert("Key ESG Issues file was successfully uploaded for processing.")/* succes handler */
                            , response => response.data.fileUploadLogs != null ? this.uploadDetails = response.data.fileUploadLogs.errors/* error handler */
                                                                                : alert("Unexpected error encountered on the server while trying to process the uploaded file!"))
                            .finally(() => rootScope.loading = false);
                    })(this.$rootScope);

                    fileReader.readAsArrayBuffer(this.selectedFile);
                }
            }
        }
    }


    var mod = angular.module(esgRatingsAdminModuleName);

    mod.controller('KeyESGIssuesController',
        ['$scope', '$rootScope', '$q', '$location', '$http', 'KeyESGIssuesService', 'notificationFactory', 'staticObjectsAdmin', KeyESGIssuesController]);
} 